package com.hqyj.springBoot.config;

import com.hqyj.springBoot.interceptor.RequestViewMappingInterceptor;
import com.hqyj.springBoot.modules.common.entity.ResourceConfigBean;
import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


//为tomcat新增一个http协议的连接器
@Configuration
//在WebMvcAutoConfiguration之后自动配置
@AutoConfigureAfter({WebMvcAutoConfiguration.class})
public class WebMvcConfig implements WebMvcConfigurer {

    //使用value注解读取配置文件中的自定义端口
    @Value("${server.http.port}")
    private int httpPort;
    //将公共静态资源文件类注入
    @Autowired
    private ResourceConfigBean resourceConfigBean;
    @Autowired
    private RequestViewMappingInterceptor requestViewMappingInterceptor;

    //创建一个可以链接80端口的连接器
    @Bean
    public Connector connector(){
        Connector connector = new Connector();
        //找到自定义配置类
        connector.setPort(httpPort);
        //协议为http协议
        connector.setScheme("http");
        return connector;
    }

    @Bean
    public ServletWebServerFactory servletWebServerFactory(){
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addAdditionalTomcatConnectors(connector());
        return tomcat;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String systemName = System.getProperty("os.name");
        //判断这个系统升级什么系统 （系统名字圈不变成小写并且如果是以win开始的就是windows系统）
        if(systemName.toLowerCase().startsWith("win")){
            registry.addResourceHandler(resourceConfigBean.getResourcePathPattern())
                    .addResourceLocations(ResourceUtils.FILE_URL_PREFIX + resourceConfigBean.getLocalPathForWindow());
        }else{
            registry.addResourceHandler(resourceConfigBean.getResourcePathPattern())
                    .addResourceLocations(ResourceUtils.FILE_URL_PREFIX + resourceConfigBean.getLocalPathForLinux());
        }
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(requestViewMappingInterceptor).addPathPatterns("/**");
    }
}
